package tedu.boot21.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tedu.boot21.entity.User;
import tedu.boot21.utils.DBUtils;

import java.sql.*;

@Controller
public class UserController {

    @RequestMapping("/reg")
    @ResponseBody
    public String reg(User user){
        try (
                Connection conn = DBUtils.getConn()
        ){
            String sql = "select id from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                return "用户已存在!!!";
            }
            String userSql = "insert into user values(null,?,?,?)";
            PreparedStatement ps1 = conn.prepareStatement(userSql);
            ps1.setString(1,user.getUsername());
            ps1.setString(2,user.getPassword());
            ps1.setString(3,user.getNick());
            ps1.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "注册成功!!!";
    }
    @RequestMapping("/login")
    @ResponseBody
    public String login(User user){
        System.out.println("user = " + user);
        try(
                Connection conn = DBUtils.getConn()
        ) {

            String sql = "select password from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ResultSet rs = ps.executeQuery();
            if(rs.next()) {
                String pwd = rs.getString(1);
                if (pwd.equals(user.getPassword())) {
                    return "登录成功!!!";
                } else
                    return "密码错误!";

            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "用户名已存在!!!";
    }
}
